/**
 * @(#)ItemServiceImpl.java, 2018/2/3.
 * <p/>
 * Copyright 2018 Kerr Wang, Inc. All rights reserved.
 * KERRWANG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package org.wangzx.exercise.service.core.impl;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wangzx.exercise.dao.ItemDao;
import org.wangzx.exercise.exception.CommonServiceException;
import org.wangzx.exercise.meta.bean.ItemBean;
import org.wangzx.exercise.meta.convertor.CommonConvertor;
import org.wangzx.exercise.meta.po.Item;
import org.wangzx.exercise.meta.po.User;
import org.wangzx.exercise.service.core.ItemCoreService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hzwangzuxiang(ahscwzx@163.com)
 */
@Service("itemCoreService")
public class ItemCoreServiceImpl implements ItemCoreService {
    static private final Logger logger = LoggerFactory.getLogger(ItemCoreServiceImpl.class);

    static private final long PAGE_SIZE = 1000L;

    @Autowired
    private ItemDao itemDao;

    @Override
    public List<ItemBean> getAllItems() {
        List<ItemBean> result = new ArrayList<>();
        long pageStart = 0L;
        long pageSize = PAGE_SIZE;
        List<ItemBean> list = null;
        list = CommonConvertor.poToBo(itemDao.getItemsByPage(pageStart, pageSize), ItemBean.class);
        while (CollectionUtils.isNotEmpty(list)) {
            result.addAll(list);
            pageStart += pageSize;
            list = CommonConvertor.poToBo(itemDao.getItemsByPage(pageStart, pageSize), ItemBean.class);
        }
        return result;
    }

    @Override
    public List<ItemBean> getAllItemsBySeller(long sellerId) {
        return CommonConvertor.poToBo(itemDao.getItemsBySeller(sellerId), ItemBean.class);
    }

    @Override
    public long insertItem(ItemBean itemBean) {
        if(itemBean == null) {
            logger.error("[op:insertItem] error, bean is null");
            return -1;
        }
        itemBean.setCreateTime(System.currentTimeMillis());
        itemBean.setUpdateTime(System.currentTimeMillis());
        Item po = CommonConvertor.boToPo(itemBean, Item.class);
        return itemDao.insert(po);
    }

    @Override
    public ItemBean getItemById(long id) {
        Item item = itemDao.getById(id);
        if(item == null) {
            logger.info("[op:getItemById] item not exist, id={}", id);
            throw new CommonServiceException();

        }
        return CommonConvertor.poToBo(item, ItemBean.class);
    }

    public boolean updateItem(ItemBean itemBean) {
        itemBean.setUpdateTime(System.currentTimeMillis());
        return itemDao.updateItem(CommonConvertor.boToPo(itemBean, Item.class));
    }

    public boolean addSellCount(long id, int num) {
        return itemDao.addSellerCount(id, num);
    }
}
